package example.com.AndroidLogin;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import android.content.Intent;

import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import example.com.AndroidLogin.R;

 
public class AndroidLogin extends Activity 
{
	    /** Called when the activity is first created. */
	
	public static final String LOG_TAG="AndroidLogin";
	Button myButton;
	EditText myText;
	TextView myError;
	EditText myPasswd;
	String authToken= null;
	String email=null;
	String passwd = null;
	String list = null;
	boolean status = false;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		    
		    
		myButton = (Button)findViewById(R.id.mybutton);
		myText = (EditText)findViewById(R.id.txt_username);
		myError = (TextView)findViewById(R.id.lbl_err);
		myPasswd = (EditText)findViewById(R.id.txt_passwd);
		
		myText.setSingleLine();
		myText.setInputType(InputType.TYPE_NULL);
		//myPasswd.setInputType(InputType.TYPE_NULL);
		myError.setInputType(InputType.TYPE_NULL);
		
		Log.v(LOG_TAG,"Input value"+myText.toString());
		        
		   
		        
		myButton.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
			    	
				HeaderIterator headerIt = null;
				InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				mgr.hideSoftInputFromWindow(myPasswd.getWindowToken(),0);
				email = myText.getText().toString();
				Log.v(LOG_TAG,"email = "+email.toString());
				passwd = myPasswd.getText().toString();
				Log.v(LOG_TAG,"Password = "+passwd.toString());
				
				
				HttpClient client = new DefaultHttpClient();
				String postURL = "https://www.google.com/accounts/ClientLogin";
				HttpPost post = new HttpPost(postURL);
				Log.v(LOG_TAG,"post value"+post.toString());
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				
				
				nvps.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE"));
				nvps.add(new BasicNameValuePair("Email", email));
				nvps.add(new BasicNameValuePair("Passwd", passwd));
				nvps.add(new BasicNameValuePair("service", "writely"));

				UrlEncodedFormEntity ent;
				String postResponseBody = null;
				try 
				{
					ent = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
					post.setEntity(ent);
					
/*					post.addHeader("testHeader","testValue");
					
					headerIt = post.headerIterator();
					
					while (headerIt.hasNext())
					{
						Log.v(LOG_TAG,"post req head: " 
							+ headerIt.nextHeader().getName() + "="
							+ headerIt.nextHeader().getValue());
					}
*/					
					HttpResponse responsePOST = client.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();
					
					headerIt = responsePOST.headerIterator();

					Header printHeader = null;
					while (headerIt.hasNext())
					{
						printHeader = headerIt.nextHeader();
						Log.v(LOG_TAG,"post resp head:" 
							+ printHeader.getName() + "="
							+ printHeader.getValue());
					}
					
					
					if (resEntity != null) 
					{
						postResponseBody = EntityUtils.toString(resEntity);
						Log.v(LOG_TAG, "post response = "+postResponseBody.toString());
					}
				} 
				
				catch (UnsupportedEncodingException e) 
				{
					e.printStackTrace();
				} 
				catch (ClientProtocolException e) 
				{
					e.printStackTrace();
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
				}
				  
				if(status = postResponseBody.startsWith("Error"))
					myError.setText("Invalid Username or Password");
				else
				{
					String[] findAuthToken;
					findAuthToken = postResponseBody.split("\n");
					
					for (int i = 0; i < findAuthToken.length; i++)
					{
						if (findAuthToken[i].contains("Auth="))
						{
							findAuthToken = findAuthToken[i].split("=");
							authToken = findAuthToken[1];
							Log.v(LOG_TAG, "AuthToken=" + authToken);
							break;
						}
					}

					try
					{
						HttpClient get_client = new DefaultHttpClient();
						HttpGet get = new HttpGet();
						get.setURI(new URI(
						"https://docs.google.com/feeds/documents/private/full"));
						Log.v(LOG_TAG,"get value"+get.toString());
						
						get.addHeader("Authorization", "GoogleLogin auth=" + authToken);
						
						headerIt = get.headerIterator();
						
						Header printHeader = null;
						while(headerIt.hasNext())
						{
							printHeader = headerIt.nextHeader();
							Log.v(LOG_TAG, "get request header: " 
								+ printHeader.getName() + "="
								+ printHeader.getValue());
						}
						
						HttpResponse responseGET = get_client.execute(get);
						HttpEntity getEntity = responseGET.getEntity();	
						if (getEntity != null)
						{
							list = EntityUtils.toString(getEntity);
							Log.v(LOG_TAG, "list as follows\n" + list);
						}
					}
					catch (UnsupportedEncodingException e) 
					{
						e.printStackTrace();
					} 
					catch (ClientProtocolException e) 
					{
						e.printStackTrace();
					} 
					catch (IOException e) 
					{
						e.printStackTrace();
					} 
					catch (URISyntaxException e) 
					{
						e.printStackTrace();
					}
					
	
					Intent i = new Intent(AndroidLogin.this, DocList.class);
					startActivity(i);    
				}
			    	                	            
			        		
			}
		    	
		});      
	       
	}
}